import Dialog from "../components/dialog";
import { saveChatting } from "../redux/action";
import store from "../redux/store";
import ReactDom from 'react-dom'

let ws = null;
let onMsgCbs = {};
let sendMsgObj = {};
let chatRecords=[];

export function initWebSocket(url, token) {
  ws = new WebSocket(url, [token])
  ws.onopen=()=>{
    chatRecords=JSON.parse(sessionStorage.getItem(store.getState().MsgMode.name));
    if(chatRecords!=null){
      for(let i=0;i<chatRecords.length;i++){
        store.dispatch(saveChatting(chatRecords[i]))
      }
      ReactDom.render(<Dialog></Dialog>, store.getState().MsgMode.box)
    }
  }
  ws.onmessage = (evt) => {
    let msg = JSON.parse(evt.data)
    onMsgCbs = {
      flag: false,
      msg: msg.message
    }
    if(msg.fromName===store.getState().MsgMode.name){
      chatRecords=JSON.parse(sessionStorage.getItem(store.getState().MsgMode.name));
      if(chatRecords==null){
        chatRecords=[];
      }
      // onMsgCbs.avatar = store.getState().MsgMode.avatar[0]
      onMsgCbs.avatar = store.getState().MsgMode.avatar[store.getState().MsgMode.avatar.length - 1]
      chatRecords[chatRecords.length]=onMsgCbs
      sessionStorage.setItem(msg.fromName, JSON.stringify(chatRecords))
      store.dispatch(saveChatting(onMsgCbs))
      ReactDom.render(<Dialog></Dialog>, store.getState().MsgMode.box)
    }
  }
}
export function sendMsg(payload) {
  sendMsgObj = {
    flag: true,
    msg: payload
  }
  chatRecords=JSON.parse(sessionStorage.getItem(store.getState().MsgMode.name))
  if(chatRecords==null){
    chatRecords=[];
  }
  sendMsgObj.avatar = store.getState().MsgMode.avatar[store.getState().MsgMode.avatar.length - 1]
  chatRecords[chatRecords.length]=sendMsgObj;
  sessionStorage.setItem(store.getState().MsgMode.name,JSON.stringify(chatRecords))
  store.dispatch(saveChatting(sendMsgObj))
  ReactDom.render(<Dialog></Dialog>, store.getState().MsgMode.box)
  ws?.send(payload);
}
export function onMsg(cb) {
  onMsgCbs.push(cb);
}
export function onClose(){
    onMsgCbs = [];
    ws.close();
}